<script setup>
import { ref, onMounted, watch } from "vue";
import {
  getClazzList,
  getClazzById,
  addClazz,
  updateClazz,
  deleteClazz,
} from "@/api/clazz";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, Edit, Delete } from "@element-plus/icons-vue";
import { getAllEmp } from "@/api/emp";

// 查询表单数据
const searchForm = ref({
  name: "",
  endDateRange: [],
  beginDate: [],
  endDate: [],
});

// 表格数据
const clazzList = ref([]);

// 分页数据
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: "",
});

// 弹窗可见性
const dialogVisible = ref(false);
// 弹窗标题
const dialogTitle = ref("新增班级");

// 表单引用
const clazzFormRef = ref(null);
// 表单数据
const clazzForm = ref({
  name: "",
  room: "",
  beginDate: "",
  endDate: "",
  masterId: "",
  subject: "",
});

// 表单校验规则
const rules = ref({
  name: [{ required: true, message: "请输入班级名称", trigger: "blur" }],
  beginDate: [{ required: true, message: "请选择开课日期", trigger: "blur" }],
  endDate: [{ required: true, message: "请选择结课日期", trigger: "blur" }],
  subject: [
    { required: true, message: "请选择学科", trigger: "change" },
    { required: true, message: "请选择学科", trigger: "blur" },
  ],
});

// 监听搜索表单日期变化
watch(
  () => searchForm.value.endDateRange,
  (newVal) => {
    if (newVal && newVal.length === 2) {
      searchForm.value.beginDate = newVal[0];
      searchForm.value.endDate = newVal[1];
    } else {
      searchForm.value.beginDate = "";
      searchForm.value.endDate = "";
    }
  }
);

// 所有员工
const empList = ref([]);
// 学科列表  Java/前端/大数据/Python/GO/嵌入式
const subjectOptions = ref([
  { value: 1, label: "Java" },
  { value: 2, label: "前端" },
  { value: 3, label: "大数据" },
  { value: 4, label: "Python" },
  { value: 5, label: "GO" },
  { value: 6, label: "嵌入式" },
]);

// 查询班级列表
const handleSearch = async () => {
  // 打印查询条件
  console.log(searchForm.value);
  // 构建查询参数，排除数组类型的字段
  const params = {
    name: searchForm.value.name,
    begin: searchForm.value.beginDate,
    end: searchForm.value.endDate, //
    page: pagination.value.currentPage,
    pageSize: pagination.value.pageSize,
  };
  // 查询班级列表
  const res = await getClazzList(params);
  if (res.code) {
    // 查询成功
    clazzList.value = res.data.rows; // 更新表格数据
    pagination.value.total = res.data.total; // 更新总记录数
  } else {
    // 查询失败
    ElMessage.error(res.msg);
  }
};

// 重置查询表单
const handleReset = () => {
  searchForm.value = {
    name: "",
    endDateRange: [],
    beginDate: "",
    endDate: "",
  };
  handleSearch(); // 重置后重新查询
};

// 分页改变事件
const handleCurrentChange = (val) => {
  pagination.value.currentPage = val; // 更新当前页码
  handleSearch(); // 重新查询
};
// 每页显示数量改变事件
const handleSizeChange = (val) => {
  pagination.value.pageSize = val; // 更新每页显示数量
  handleSearch(); // 重新查询
};

// 新增班级
const handleAdd = () => {
  // 1.清空表单验证信息
  if (clazzFormRef.value) {
    clazzFormRef.value.resetFields();
  }
  // 2.清空表单数据
  clazzForm.value = {
    name: "",
    room: "",
    beginDate: "",
    endDate: "",
    empId: "",
    subject: "",
  };
  // 3.设置弹窗标题
  dialogTitle.value = "新增班级";
  // 4.显示弹窗
  dialogVisible.value = true;
};

// 编辑班级
const handleEdit = async (id) => {
  // 清空表单验证信息
  if (clazzFormRef.value) {
    clazzFormRef.value.resetFields();
  }
  // 1. 根据id查询班级
  const res = await getClazzById(id);
  if (res.code) {
    // 查询成功
    clazzForm.value = res.data;
    dialogVisible.value = true; // 显示弹窗
    dialogTitle.value = "修改班级"; // 设置弹窗标题
  } else {
    // 查询失败
    ElMessage.error(res.msg);
  }
};

// 保存班级
const save = async () => {
  // 1. 校验表单
  await clazzFormRef.value.validate();
  let res = null;
  // 根据id判断是新增还是修改
  if (clazzForm.value.id) {
    // 修改
    res = await updateClazz(clazzForm.value);
  } else {
    // 新增
    res = await addClazz(clazzForm.value);
  }
  if (res.code) {
    // 3. 保存成功，关闭对话框，刷新列表
    ElMessage.success("保存成功");
    dialogVisible.value = false;
    handleSearch();
  } else {
    // 4. 保存失败，显示错误信息
    ElMessage.error(res.msg);
  }
};

// 删除班级
const handleDelete = (id) => {
  // 1. 弹出确认框
  ElMessageBox.confirm("确定要删除该班级吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    // 2. 删除班级
    const res = await deleteClazz(id);
    if (res.code) {
      // 3. 删除成功，刷新列表
      ElMessage.success("删除成功");
      handleSearch();
    } else {
      ElMessage.error(res.msg);
    }
  });
};

// 获取所有员工
const getEmpList = async () => {
  const res = await getAllEmp();
  if (res.code) {
    // 查询成功
    empList.value = res.data;
  } else {
    ElMessage.error(res.msg);
  }
};

// 初始化表格数据
onMounted(() => {
  handleSearch();
  getEmpList();
});
</script>

<template>
  <div class="clazz-management">
    <h1>班级管理</h1>
    <!-- 查询表单 -->
    <el-form :model="searchForm" class="search-form">
      <el-form-item label="班级名称" prop="className">
        <el-input
          v-model="searchForm.name"
          placeholder="请输入班级名称"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item label="结课时间" prop="endDateRange">
        <el-date-picker
          v-model="searchForm.endDateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
        ></el-date-picker>
      </el-form-item>
      <el-form-item class="form-actions">
        <el-button
          type="primary"
          size="large"
          class="action-btn"
          @click="handleSearch"
          >查询</el-button
        >
        <el-button
          type="info"
          size="large"
          class="action-btn"
          @click="handleReset"
          >清空</el-button
        >
      </el-form-item>
    </el-form>

    <!-- 新增班级按钮 -->
    <div class="action-bar">
      <el-button type="primary" size="large" :icon="Plus" @click="handleAdd"
        >新增班级</el-button
      >
    </div>

    <!-- 表格 -->
    <el-table :data="clazzList" border style="width: 100%">
      <el-table-column
        type="index"
        label="序号"
        width="60"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="name"
        label="班级名称"
        width="160"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="room"
        label="班级教室"
        width="125"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="masterName"
        label="班主任"
        width="150"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="beginDate"
        label="开课时间"
        width="180"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="endDate"
        label="结课时间"
        width="180"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="status"
        label="状态"
        width="100"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="updateTime"
        label="最后操作时间"
        width="220"
        align="center"
      ></el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="{ row }">
          <el-button
            type="primary"
            size="medium"
            :icon="Edit"
            @click="handleEdit(row.id)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            size="medium"
            :icon="Delete"
            @click="handleDelete(row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页条 -->
    <el-pagination
      class="pagination"
      v-model:current-page="pagination.currentPage"
      v-model:page-size="pagination.pageSize"
      :page-sizes="[5, 10, 20, 50]"
      :total="pagination.total"
      layout="total, sizes, prev, pager, next, jumper"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    ></el-pagination>
  </div>

  <!-- 新增班级弹窗 -->
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="600px"
    :close-on-click-modal="false"
  >
    <el-form
      :model="clazzForm"
      :rules="rules"
      label-width="100px"
      label-position="right"
      ref="clazzFormRef"
    >
      <el-form-item label="班级名称" prop="name">
        <el-input
          v-model="clazzForm.name"
          placeholder="请输入班级名称"
          clearable
        />
      </el-form-item>

      <el-form-item label="班级教室" prop="room">
        <el-input
          v-model="clazzForm.room"
          placeholder="请输入班级教室"
          clearable
        />
      </el-form-item>

      <el-form-item label="开课时间" prop="beginDate">
        <el-date-picker
          v-model="clazzForm.beginDate"
          type="date"
          placeholder="选择开课时间"
          value-format="YYYY-MM-DD"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="结课时间" prop="endDate">
        <el-date-picker
          v-model="clazzForm.endDate"
          type="date"
          placeholder="选择结课时间"
          value-format="YYYY-MM-DD"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="班主任" prop="masterId">
        <el-select
          v-model="clazzForm.masterId"
          placeholder="请选择班主任"
          style="width: 100%"
          clearable
        >
          <el-option
            v-for="emp in empList"
            :key="emp.id"
            :label="emp.name"
            :value="emp.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="学科" prop="subject">
        <el-select
          v-model="clazzForm.subject"
          placeholder="请选择学科"
          style="width: 100%"
          clearable
        >
          <el-option
            v-for="subject in subjectOptions"
            :key="subject.value"
            :label="subject.label"
            :value="subject.value"
          />
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="save" class="footer-btn"
          >保存</el-button
        >
        <el-button @click="dialogVisible = false" class="footer-btn"
          >取消</el-button
        >
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.clazz-management {
  padding: 24px;
  min-height: 100vh;
}

h1 {
  font-family: "SimSun";
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.search-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

.search-form .el-form-item {
  margin-bottom: 0;
}

.action-bar {
  margin-bottom: 20px;
}

/* 表格样式 */
:deep(.el-table) {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  border-radius: 4px;
  overflow: hidden;
}

/* 表头样式 */
:deep(.el-table__header th) {
  background-color: #f8f9fa;
  font-size: 15px;
  font-weight: 600;
  color: #606266;
  height: 50px;
}

/* 表格内容样式 */
:deep(.el-table__body td) {
  font-size: 14px;
  color: #606266;
  height: 48px;
}

/* 斑马纹效果 */
:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: #fafafa;
}

/* 按钮样式 */
:deep(.el-button) {
  font-size: 14px;
  padding: 8px 15px;
}

/* 表单标签样式 */
:deep(.el-form-item__label) {
  font-size: 16px !important;
  color: #606266;
  font-weight: 500;
}

/* 输入框样式 */
:deep(.el-input__inner) {
  height: 40px;
  line-height: 40px;
  font-size: 14px;
}

/* 日期选择器样式 */
:deep(.el-date-editor .el-range-separator) {
  line-height: 32px;
}

.form-actions {
  margin-left: 50px; /* 使按钮组靠右 */
}

.action-btn {
  width: 100px; /* 增加按钮宽度 */
  border-radius: 4px; /* 稍微扁平化的圆角 */
  box-shadow: none; /* 移除默认阴影使更扁平 */
  border: 1px solid #dcdfe6; /* 统一边框样式 */
}

/* 主按钮扁平化效果 */
:deep(.el-button--primary.action-btn) {
  background-color: #409eff;
  border-color: #409eff;
}

/* 分页样式 */
.pagination {
  margin-top: 24px;
  text-align: right;
  padding: 16px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

:deep(.el-pagination__total),
:deep(.el-pagination__jump) {
  font-size: 14px;
}

/* 主按钮悬停效果 */
:deep(.el-button--primary) {
  background-color: #409eff;
  border-color: #409eff;
}

:deep(.el-button--primary:hover) {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

/* 危险按钮悬停效果 */
:deep(.el-button--danger) {
  background-color: #f56c6c;
  border-color: #f56c6c;
}

:deep(.el-button--danger:hover) {
  background-color: #f78989;
  border-color: #f78989;
}

.dialog-footer {
  text-align: center; /* 使按钮居中 */
  margin-top: -20px; /* 将按钮整体靠上 */
}

.dialog-footer .footer-btn {
  padding: 12px 24px; /* 增加按钮内边距 */
  font-family: "SimSun";
  font-size: 18px; /* 增大字体大小 */
  min-width: 120px; /* 统一按钮宽度 */
  border-radius: 4px; /* 增加圆角 */
  font-weight: 520; /* 字体加粗 */
  margin: 0 18px; /* 增加按钮之间的间距 */
  transition: all 0.3s ease; /* 添加过渡效果 */
  height: 32px;
}

/* 取消按钮样式 */
.dialog-footer .el-button:not(.el-button--primary) {
  background-color: #f0f0f0; /* 浅灰色背景 */
  border-color: #d9d9d9; /* 灰色边框 */
  color: #606266; /* 深灰色文字 */
}

.dialog-footer .el-button:not(.el-button--primary):hover {
  background-color: #e6e6e6; /* 悬停时背景变深 */
  border-color: #c0c0c0; /* 悬停时边框变深 */
}

/* 保存按钮样式 */
.dialog-footer .el-button--primary {
  background-color: #409eff; /* 蓝色背景 */
  border-color: #409eff; /* 蓝色边框 */
  color: #fff; /* 白色文字 */
}

.dialog-footer .el-button--primary:hover {
  background-color: #66b1ff; /* 悬停时背景变浅 */
  border-color: #66b1ff; /* 悬停时边框变浅 */
}
</style>
